package com.nervenets.general.config;

import com.nervenets.general.filter.NerveNetsRequestWrapperFilter;
import com.nervenets.general.filter.SecretUrlFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 2020/6/23 17:52 created by Joe
 **/
@Configuration
public class FilterConfig {
    @Resource
    private ApplicationProperties applicationProperties;

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(applicationProperties.getCors().isAllowCredentials());
        config.setAllowedOrigins(Arrays.asList(applicationProperties.getCors().getAllowedOrigins()));
        config.setAllowedHeaders(Arrays.asList(applicationProperties.getCors().getAllowedHeaders()));
        config.setAllowedMethods(Arrays.asList(applicationProperties.getCors().getAllowedMethods()));
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

    @Bean
    public FilterRegistrationBean<NerveNetsRequestWrapperFilter> nerveNetsRequestWrapperFilterRegistration() {
        FilterRegistrationBean<NerveNetsRequestWrapperFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(nerveNetsRequestWrapperFilter());
        registration.addUrlPatterns("*");
        registration.setName("nerveNetsRequestWrapperFilter");
        return registration;
    }

    @Bean(name = "nerveNetsRequestWrapperFilter")
    public NerveNetsRequestWrapperFilter nerveNetsRequestWrapperFilter() {
        return new NerveNetsRequestWrapperFilter(applicationProperties);
    }

    @Bean
    public FilterRegistrationBean<SecretUrlFilter> secretUrlFilterRegistration() {
        FilterRegistrationBean<SecretUrlFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(secretUrlFilter());
        ApplicationProperties.SecretUrl secretUrl = applicationProperties.getSecretUrl();
        registration.addUrlPatterns(secretUrl.getUris());
        registration.addUrlPatterns(ApplicationProperties.SecretUrl.LOGIN_ACTION);
        registration.setName("secretUrlFilter");
        return registration;
    }

    @Bean(name = "secretUrlFilter")
    public SecretUrlFilter secretUrlFilter() {
        return new SecretUrlFilter(applicationProperties);
    }
}
